#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "../Common/Util.hpp"
#include "../Common/Log.hpp"
namespace ns_compilier
{
    using namespace ns_log;
    using namespace FileTool;
    class Compilier
    {
    public:
        Compilier()
        {}
        ~Compilier()
        {}
        static bool CompilierFunc(const std::string &filename)
        {
            //不关心退出码！
            // 用子进程去程序替换
            pid_t pid = fork();
            if (pid < 0)
            {
                LOG(FATAL, "fork error\n");
                exit(1);
            }
            else if (pid == 0)
            {
                umask(0); // 清零文件掩码
                int sterror_fd = open(FileSplice::SpliceCompileStderrLog(filename).c_str(), O_CREAT | O_WRONLY, 0644);
                if (sterror_fd < 0)
                {
                    LOG(WARNING, "创建错误信息日志文件失败！\n");
                    exit(3);
                }
                ::dup2(sterror_fd, 2);
                ::execlp("g++", "g++", "-o", FileSplice::SpliceExePathName(filename).c_str(), FileSplice::SpliceSrcPathName(filename).c_str(),"-D","COMPLIER_RUN","-std=c++17",nullptr);
                LOG(ERROR, "程序替换失败！\n");
                exit(2); 
            }
            else
            {
                int res = waitpid(pid, nullptr, 0);
                if (FileIsExists::IsFileExists(FileSplice::SpliceExePathName(filename)))
                {
                    LOG(INFO, "%s--编译成功!\n", FileSplice::SpliceSrcPathName(filename).c_str());
                    return true;
                }
            }
            LOG(WARNING, "编译失败！没有形成的可执行程序！\n");
            return false;
        }
    };
}